package com.group18.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.group18.entity.AccountUser;
import com.group18.service.AccountUserService;


/**
 * Servlet implementation class toCharts
 */
@WebServlet("/DoCharts")
public class DoCharts extends HttpServlet {
	private static final long serialVersionUID = 1L;
		AccountUserService aus = new AccountUserService();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DoCharts() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//从客户端获得一个session的对象
		HttpSession session = request.getSession();
		int family_id = (int)session.getAttribute("family_id");
		String year = request.getParameter("year");//key
		String month = request.getParameter("month");
		
		//格式化日期、转换日期格式
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Date time = null;
		if(year != null && month != null){
			try {
				time = sdf.parse(year+"-"+month);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			time = new Date();
		}
		int dayCount = getDaysOfMonth(time);//获取所选年月有多少天
		
		//折线图收入
		List<String> dataIn = new ArrayList<>();
		//折线图支出
		List<String> dataOut = new ArrayList<>();
		//折线图x轴
		List<String> date = new ArrayList<>();
		//饼图标签数据
		List<String> label = new ArrayList<>();
		
		//获取所有收入支出数据
		AccountUser au = new AccountUser();
		au.setFamily_id(family_id);
		List<AccountUser> alist = aus.selectAllAccountByFamily_id(au);
		
		//筛选符合日期的收入支出数据
		int monthIn[] = new int[12];
		int monthOut[] = new int[12];
		int dayIn[] = new int[dayCount];
		int dayOut[] = new int[dayCount];
		//收入标签和支出标签
		HashMap<Object, Object> inLabel = new HashMap<>();
		HashMap<Object, Object> outLabel = new HashMap<>();
		int in = 0;
		int out = 0;
		int yearIn = 0;
		int yearOut = 0;
		int yueIn = 0;
		int yueOut = 0;
		for (AccountUser list : alist) {
			if(month.equals("00")){
				//统计年收入支出
				String str[] = list.getDate().split("-");
				if(str[0].equals(year)){
					if(list.getState().equals("收入")){
						//年收入
						monthIn[Integer.parseInt(str[1])] += list.getMoney();
						if(inLabel.get(list.getLabel()) != null) {
							inLabel.put(list.getLabel(), (double)inLabel.get(list.getLabel())+list.getMoney());
						}else {
							inLabel.put(list.getLabel(), list.getMoney());
						}
					}else {
						//年支出
						monthOut[Integer.parseInt(str[1])] += list.getMoney();
						if(outLabel.get(list.getLabel()) != null) {
							outLabel.put(list.getLabel(), (double)outLabel.get(list.getLabel())+list.getMoney());
						}else {
							outLabel.put(list.getLabel(), list.getMoney());
						}
						
					}
				}
			}else{
				//统计月收入支出
				String str[] = list.getDate().split("-");
				if(str[0].equals(year) && str[1].equals(month)){
					if(list.getState().equals("收入")){
						dayIn[Integer.parseInt(str[2])] += list.getMoney();
						if(inLabel.get(list.getLabel()) != null) {
							inLabel.put(list.getLabel(), (double)inLabel.get(list.getLabel())+list.getMoney());
						}else {
							inLabel.put(list.getLabel(), list.getMoney());
						}
					}else {
						dayOut[Integer.parseInt(str[2])] += list.getMoney();
						if(outLabel.get(list.getLabel()) != null) {
							outLabel.put(list.getLabel(), (double)outLabel.get(list.getLabel())+list.getMoney());
						}else {
							outLabel.put(list.getLabel(), list.getMoney());
						}
					}
				}
			}
		}
		if(month.equals("00")) {
			for(int i = 0;i < 12;i++){
				//折线图数据
				dataIn.add(monthIn[i]+"");
				dataOut.add(monthOut[i]+"");
				date.add("'"+(i+1)+"月'");
				//饼图数据
				yearIn += monthIn[i];
				yearOut += monthOut[i];
			}
			in = yearIn;
			out = yearOut;
		}else{
			for(int i = 0;i < dayCount;i++){
				//折线图数据
				date.add("'"+(i+1)+"日'");
				dataIn.add(dayIn[i]+"");
				dataOut.add(dayOut[i]+"");
				//饼图数据
				yueIn += dayIn[i];
				yueOut += dayOut[i];
			}
			in = yueIn;
			out = yueOut;
		}
		//饼图
		Iterator itr = inLabel.entrySet().iterator();
		while(itr.hasNext()) {
			Entry entry = (Entry) itr.next();
			String key = (String) entry.getKey();
			String value = entry.getValue()+"";
			label.add("{value:"+value+",name:'"+key+"'}");
		}
		itr = outLabel.entrySet().iterator();
		while(itr.hasNext()) {
			Entry entry = (Entry) itr.next();
			String key = (String) entry.getKey();
			String value = entry.getValue()+"";
			label.add("{value:"+value+",name:'"+key+"'}");
		}
		
		//
		request.setAttribute("dataIn", dataIn.toString());
		request.setAttribute("dataOut", dataOut.toString());
		request.setAttribute("date", date.toString());
		request.setAttribute("label", label.toString());
		request.setAttribute("year", year);
		request.setAttribute("month", month);
		request.setAttribute("in", in);
		request.setAttribute("out", out);
		request.getRequestDispatcher("/WEB-INF/jsp/chart.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
	//年
	public static int getYear(Date date) {  
        Calendar calendar = Calendar.getInstance();  
        calendar.setTime(date);  
        return calendar.get(Calendar.YEAR);  
    }
	
	//获取某个月有多少天
	public static int getDaysOfMonth(Date date){
		Calendar calendar = Calendar.getInstance();  
        calendar.setTime(date);  
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH); 
	}

}
